<script setup>
import { ref,toRefs,reactive,onBeforeMount } from 'vue'
import { useItem } from '../../../store/index.js';
import { ElMessage } from 'element-plus';
import String2List from '../String2List.vue'
import { storeToRefs } from 'pinia'
import { deleteTableRow } from '../../../utils/utils';
import StringOrNumber from '../StringOrNumber.vue';
import Port from './container/Port.vue';
import HealthCheck from './container/HealthCheck.vue';
import Env from './container/Env.vue'
import LifeCycle from './container/LifeCycle.vue'
import VolumeMounts from './container/VolumeMounts.vue'
const { item } = storeToRefs(useItem())
const useItemer = useItem()

const props = defineProps({
    containerType: {
        type: String,
        // init
        default: 'container'
    },
    method: {
        type: String,
        default: 'Create'
    },
    resourceType: {
        type: String,
        default: 'Deployment'
    },
})

let containerCount = ref(0)
const data = reactive({
    containers: [],
    container: {
        name: `${props.containerType}-${containerCount.value}`,
        image: "",
        tty: false,
        workingDir: "",
        imagePullPolicy: "IfNotPresent",
        // 在编辑的时候需要特殊处理
        resources: {
            limits: {
                memory: '1024Mi',
                cpu: 1
            },
            requests: {
                memory: '128Mi',
                cpu: '100m'
            }
        },
        ports: [],
        lifecycle: {},
        volumeMounts: [],
        env: [],
        envFrom: []
    },
    options: {
        imagePullPolicy: [
            {
                label: "总是下载",
                value: "Always"
            },
            {
                label: "有了就不下载",
                value: "IfNotPresent"
            },
            {
                label: "从不下载",
                value: "Never"
            },
        ]
    }
})
onBeforeMount(() => {
    if (props.containerType == 'init') {
        // console.log("props.containerType",props.containerType)
        data.containers = useItemer.item.spec.template.spec.initContainers
        if (data.containers == null || data.containers == undefined) {
            data.containers = []
        }
    } else { // 标准容器
        // console.log("props.containerType",props.containerType)
        data.containers = useItemer.item.spec.template.spec.containers
        containerCount.value = data.containers.length
        if (containerCount.value == 0) {
            // data.containers.push(JSON.parse(JSON.stringify(data.container)))
            // console.log(containerCount.value)
            addTab()
        }
    }
    if (props.method != 'Create') { //判断是否缺失资源配置的参数
        data.containers.forEach((container) => {
            if(container.env == undefined){
                container.env = []
            }
            if(container.envFrom == undefined){
                container.envFrom = []
            }
            if(container.ports == undefined){
                container.ports= []
            }
            if(container.volumeMounts == undefined){
                container.volumeMounts= []
            }
            if(container.resources.limits == undefined){
                container.resources.limits = {}
            }
            if(container.resources.requests == undefined){
                container.resources.requests = {}
            }
            if(container.lifecycle == undefined) {
                container.lifecycle= {}
            }
        })
    }
})
const removeTab = (targetName) => {
    if (data.containers.length == 1 && props.containerType == 'container') {
        ElMessage.warning("至少存在一个容器")
        return
    }
    console.log("target:", targetName)
    if (targetName == editableTabsValue.value) {
        // 如果相等说明删除是当前的位置
        editableTabsValue.value = 0
    } else if (targetName < editableTabsValue.value) {
        editableTabsValue.value --
    }
    deleteTableRow(data.containers, targetName)
}

// 添加容器的方法
const addTab = () => {
    // 先把容器的总数量+1
    containerCount.value++
    // 定义新容器的名字
    const containerName = `${props.containerType}-${containerCount.value}`
    // 定义一个新容器
    const newContainer = JSON.parse(JSON.stringify(data.container))
    // 更改容器的名字
    newContainer.name = containerName
    // 添加容器到数组中
    data.containers.push(newContainer)
    editableTabsValue.value = data.containers.length - 1
}

const rules = reactive({
    name: [
        {required: true, message: '请输入容器名称', trigger: 'blur'}
    ],
    image: [
        {required: true, message: '请输入容器镜像地址', trigger: 'blur'},
    ],
})
const editableTabsValue = ref(0)
const activeName = ref('basic')
const {containers, options} = toRefs(data)

</script>

<template>
    <div style="display: flex;justify-content: flex-end;">
        <el-button link type="primary" @click="addTab()">
            添加
        </el-button>
    </div>
    <el-tabs
        v-model="editableTabsValue"
        class="demo-tabs"
        closable
        @tab-remove="removeTab"
    >
        <el-tab-pane
        v-for="(item,index) in containers"
        :key="index"
        :index="index"
        :label="item.name"
        :name="index"
        >
            <el-tabs v-model="activeName" tabPosition="left" class="demo-tabs">
                <el-tab-pane label="常用配置" name="basic">
                    <!-- 容器的名字、终端、工作目录 -->
                    <el-row :gutter="20">
                        <!-- 名称 -->
                        <el-col :span="12">
                            <el-form-item label="容器名称" :rules="rules.name" :prop="(props.containerType!='init'?'spec.template.spec.containers.'+index+'.name':'spec.template.spec.initContainers.'+index+'.name')" required>
                                <el-input v-model.trim="item.name" placeholder="请输入资源名称" />
                            </el-form-item>
                        </el-col>
                        <!-- 工作目录 -->
                        <el-col :span="6">
                            <el-form-item label="工作目录" prop="item.workingDir">
                                <el-input v-model.trim="item.workingDir" placeholder="自定义工作目录" />
                            </el-form-item>
                        </el-col>
                        <!-- 分配终端 -->
                        <el-col :span="6">
                            <el-form-item label="分配终端" prop="item.tty">
                                <el-switch v-model="item.tty" />
                            </el-form-item>
                        </el-col>
        
                    </el-row>
                    <!-- 镜像地址、镜像下载策略 -->
                    <el-row :gutter="20">
                        <el-col :span="18">
                            <el-form-item label="镜像地址" :rules="rules.image" :prop="(props.containerType!='init'?'spec.template.spec.containers.'+index+'.image':'spec.template.spec.initContainers.'+index+'.image')" required>
                                <el-input v-model.trim="item.image"  placeholder="请输入镜像地址"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="镜像下载策略" prop="item.imagePullPolicy">
                                <el-select v-model="item.imagePullPolicy" placeholder="镜像下载策略">
                                <el-option
                                v-for="s in options.imagePullPolicy"
                                :key="s.value"
                                :label="s.label"
                                :value="s.value"
                                />
                            </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!-- resources -->
                    <el-row :gutter="20">
                        <el-col :span="6" title="容器申请的最小内存, 对应requests.memory">
                            <el-form-item label="最小内存" prop="item.resources.requests.memory">
                                <StringOrNumber input-width="140px" v-model:data="item.resources.requests.memory" placeholder="内存最小请求量,可选"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6"  title="容器可用的最大内存, 对应limits.memory">
                            <el-form-item label="最大内存" prop="item.resources.limits.memory">
                                <StringOrNumber input-width="140px" v-model:data="item.resources.limits.memory" placeholder="内存最大使用量,可选"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" title="容器申请的最小CPU, 对应requests.cpu">
                            <el-form-item label="最小CPU" prop="item.resources.requests.cpu">
                                <StringOrNumber input-width="140px" v-model:data="item.resources.requests.cpu" placeholder="CPU最小请求量,可选"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6"  title="容器可用的最大CPU, 对应limits.cpu" >
                            <el-form-item label="最大CPU" prop="item.resources.limits.cpu">
                                <StringOrNumber input-width="140px" v-model:data="item.resources.limits.cpu" placeholder="CPU最大使用量,可选"/>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!-- 启动命令和命令参数 -->
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="启动命令" prop="item.command">
                                <String2List v-model:data="item.command" placeholder="自定义启动命令, 对应entrypoint"></String2List>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="启动参数" prop="item.args">
                                <String2List v-model:data="item.args" placeholder="自定义启动参数, 对应cmd"></String2List>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane v-if="props.containerType == 'container' && props.resourceType != 'CronJob'" label="端口配置" name="ports">
                    <Port :ports="item.ports"></Port>
                </el-tab-pane>
                <el-tab-pane v-if="props.containerType == 'container' && props.resourceType != 'CronJob'" label="健康检查" name="health">
                    <HealthCheck :container-type="props.containerType" :container="item" :container-index="index"></HealthCheck>
                </el-tab-pane>
                <el-tab-pane label="环境变量" name="env">
                    <Env :env="item.env" :env-from="item.envFrom"></Env>
                </el-tab-pane>
                <el-tab-pane label="存储挂载" name="volume">
                    <VolumeMounts :volumeMounts="item.volumeMounts"></VolumeMounts>
                </el-tab-pane>
                <el-tab-pane v-if="props.containerType == 'container' && props.resourceType != 'CronJob'" label="生命周期" name="lifecycle">
                    <LifeCycle :container="item" :container-index="index" :container-type="props.containerType"></LifeCycle>
                </el-tab-pane>
            </el-tabs>
        </el-tab-pane>
    </el-tabs>
</template>

<style scoped>
</style>